import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Button, Modal, Input, DatePicker } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import { formatMessage } from 'umi-plugin-react/locale';
import SelectForm from '@/components/SelectForm';
import RightDraw from '@/components/RightDraw';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import ManageList from '@/components/ManageList';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import TableButtons from '@/components/TableButtons';
import StandardTable from '@/components/StandardTable';
import AdSearch from '@/components/AdSearch';
import { allDictList } from '@/utils/constans';
import SearchSelect from '@/components/SearchSelect';
import AntdDatePicker from '@/components/AntdDatePicker';
import FileImport from '@/components/FileImport';

import { columnsDriver, columns1, supplierColumns } from '@/pages/Common/common';
import { vitifyCheck, queryPerson, queryDict, formateDateToMin, formatPrice } from '@/utils/common';
import { beWork, beAssume,processMode,confirmState,handling } from '@/utils/constans';
import EndorseDetails from './EndorseDetails';



import ArchivesDetail from '../../FleetManage/Archives/ArchivesDetail';
import ArchivesOneTeamDetail from '../../FleetManage/Archives/ArchivesOneTeamDetail';
import ArchivesDetailHK from '../../FleetManage/Archives/ArchivesDetailHK';
import ArchivesDetailEmpty from "../../FleetManage/Archives/ArchivesDetailEmpty";
import EmptyArchivesForm from '../../FleetManage/Archives/EmptyArchivesForm';
import {
    allDispatchType,
    selectEndorseList,
    saveAllValues,
    renderTableAdSelect,
    renderTableAdSearch,
    codes,
    archivesStatusList,
    allUrl,
    routeUrl,
    selectArchivesDetailAndInfo,
    checkConfirm,
} from './utils';
import { is } from '@babel/types';


const confirm = Modal.confirm;

const dateFormat = 'YYYY-MM-DD';
const dateFormatByM = 'YYYY-MM';
const { MonthPicker } = DatePicker;

@ManageList

@connect(({ Endorse, loading, component }) => ({
    Endorse,
    endorseList:Endorse.endorseList,
    dictObject: component.dictObject,
    searchValue: component.searchValue,
    formValues: Endorse.formValues,
    loading: loading.effects[allDispatchType.list],
}))
@Form.create()
export default class EndorseList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            detailId: '',
            visible: false,

            expandForm: false,
            archivesInfo: {},
            recordStatus: '',
            selectedRows: [],
            company: [],
            cars: [],
            drivers: [],
            companyType: '',
            isHK: false,
            visibleEmpty: false,
            businessType: '',
            visibleFile:false,
            param:{},
        };
        this.className = 'archives-table';
    }

    componentWillMount() {
        // 查询字典项
        const allDict = [allDictList.currencyType,];
        queryDict({ props: this.props, allDict });
    }

    componentDidMount() {
        const { form, formValues } = this.props
        formValues.handlingInformation='FINISHED'
       saveAllValues({ payload: { formValues }, props: this.props });
       selectEndorseList({ payload:formValues , props: this.props });
       //this.EndorseList()
    }

    /**
     * form 查找条件 重置
     */
    handleFormReset = () => {
        const { form, formValues } = this.props
        const props = { props: this.props };
        this.setState({
           
            cars: [],
            drivers: [],
        });
        form.resetFields();
        saveAllValues({ payload: { formValues: {} }, ...props });
        selectEndorseList({ ...props });
    };

    /**
     * form 查找条件 查询
     */
    handleSearch = formValues => {
        // if (!formValues) return;
        const {  cars, drivers } = this.state;
        const {  handlingDate , trafficOffenceTime ,  ...param } = formValues;
        
        if (cars.length > 0) {
            const vehicleId = cars.map(v => {
                return v.id;
            });
            param.vehicleId = vehicleId.join(',');
        } else {
            param.vehicleId = '';
        }
        if (drivers.length > 0) {
            param.driverId = drivers[0].id;
        } else {
            param.driverId = ''
        }
        

        if (handlingDate&&handlingDate.length>0) {
            param.handlingStartDate  = moment(handlingDate[0]).format(dateFormat);
            param.handlingEndDate = moment(handlingDate[1]).format(dateFormat);
        }else{
            param.handlingStartDate=''
            param.handlingEndDate=''
        }
        if (trafficOffenceTime&&trafficOffenceTime.length>0) {
            param.trafficOffenceStartTime= moment(trafficOffenceTime[0]).format(dateFormat);
            param.trafficOffenceEndTime = moment(trafficOffenceTime[1]).format(dateFormat);
        }else{
            param.trafficOffenceStartTime=''
            param.trafficOffenceEndTime=''

        }
       

        const params = { props: this.props, payload: param };
        console.log('params-------',params)
        this.setState({param})
        saveAllValues({ payload: { formValues: param }, props: this.props });
        selectEndorseList(params);
    };

    /**
     * table 表格 分页操作
     */
    handleStandardTableChange = param => {
        const { formValues } = this.props;
        
        selectEndorseList({ payload: { ...formValues, ...param }, props: this.props });
    };

    //详情
    showDetail = (e, record) => {
        
        e.stopPropagation();
        const { id, } = record;
        this.setState({detailId:id})
        this.handleStateChange([  { detailId: id }, { visible: true }]);
    };

    handleStateChange = (options = []) => {
        console.log('options==',options)
        options.map(item => {
            this.setState(item);
        });
    };

    
    //新建违章记录
    motorcadeEmpty=(YCD)=>{
        router.push(routeUrl.add)
    }
    //编辑
    handleEdit = () => {
        const { detailId } = this.state;
        this.handleStateChange([{ visible: false }]);
        
        router.push(`${routeUrl.edit}/${detailId}`)

        
    };

    columns = [
        {
            title: '车牌号',
            dataIndex: 'vehicleName',
            render: (text, record) => (
                <AdButton
                    mode="a"
                    onClick={e => this.showDetail(e, record)}
                    text={text}
                    code={codes.showDetail}
                />
            ),
            fixed: this.props.isMobile ? false : true,
        },
        {
            title: '驾驶员',
            dataIndex: 'driverName',
            width: 100,
            render: text =>
                renderTableAdSelect({
                    props: this.props,
                    value: text || 'INLAND',
                    key: allDictList.businessType
                })
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: 100,
            render: text =>
            <AdSelect
                onlyRead={true}
                value={text}
                data={confirmState}
            />
                // renderTableAdSelect({ props: this.props, value: text, data: archivesStatusList }),
        },
        {
            title: '是否在职',
            dataIndex: 'beWork',
            width: 100,
            render: text =>
            <AdSelect
                onlyRead={true}
                value={text}
                data={beWork}
            />
                // renderTableAdSelect({ props: this.props, value: text, data: archivesStatusList }),
        },
        {
            title: '交通违法时间',
            dataIndex: 'trafficOffenceTime',
        },
        // {
        //   title: '车挂',
        //   dataIndex: 'cartHangingName',
        // },
        {
            title: '交通违法地点',
            dataIndex: 'trafficOffenceAddress',
            render: text => <span title={text}>{text}</span>
        },
        {
            title: '交通违法项目',
            dataIndex: 'trafficOffenceProject',
            render: text => <span title={text}>{text}</span>,
            width: 300,
        },
        {
            title: '罚款',
            dataIndex: 'forfeit',
            width: 100,
            render: text => <span>{formatPrice(text)}</span>,
        },{
            title: '处理方式',
            dataIndex: 'processMode',
            width: 100,
            render: text =>
            <AdSelect
                onlyRead={true}
                value={text}
                data={processMode}
            />
        },
        {
            title: '记分',
            dataIndex: 'scoring',
            width: 50,
        },
        {
            title: '执法单位',
            dataIndex: 'lawEnforcement',
        },
        {
            title: '处理情况',
            dataIndex: 'handlingInformation',
            width: 100,
            render:(text)=>
            <AdSelect
                onlyRead={true}
                value={text}
                data={handling}
            />
        },
        {
            title: '处理日期',
            dataIndex: 'handlingDate',
        },
        {
            title: '是否公司承担',
            dataIndex: 'beAssume',
            render: text =>
            <AdSelect
                onlyRead={true}
                value={text}
                data={beAssume}
            />
        },
       
    ];

    
     //删除违章
     removeEndorse = () => {
        const { dispatch ,formValues } = this.props;
        const { detailId, visible } = this.state;
        confirm({
            title: '确定要删除这条数据吗？',
            content: ' ',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
                dispatch({
                    type: allDispatchType.remove,
                    payload: { id: detailId },
                    callback: (res) => {
                        if (!res) return;
                        this.setState({ visible: false, selectedRows: [] });
                        // this.getSelectList(formValues);
                        selectEndorseList({ payload: formValues , props: this.props })

                    },
                });
            },
        });
    };
    

    // 确认、提交
    endorseConfirm = (type,single) => {
        const { dispatch ,formValues} = this.props;
        const { detailId, selectedRows,  } = this.state;
        
        let id=detailId
        let ids=single===1?[id]:selectedRows.map(v => {
            return v.id;
        });
        const checked = selectedRows.some(v => {
            if (v.status !== "CONFIRM") {
                return true;
            } else {
                return false;
            }
        });
        if (checked) {
            prompt({ title: '温馨提示', content: '请选择状态为待提交的违章记录', type: 'warn' });
            return;
        }
        const unit={
            // 确认
            callConfirm:()=>{
                dispatch({
                    type: allDispatchType.confirm,
                    payload: { id},
                    callback: (data) => {
                        
                        this.setState({ visible:false, selectedRows: [] });
                        selectEndorseList({ payload: formValues , props: this.props })
                    },
                });
            },
            //提交、批量提交
            callCommit:(tips = "")=>{
                confirm({
                    title: `${tips}提交后数据将不能进行修改，是否进行提交？`,
                    content: ' ',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        dispatch({
                            type: allDispatchType.commit,
                            payload: { ids},
                            callback: (data) => {
                                // console.log('data=====2=======',data)
                                
                                this.setState({ visible: false, selectedRows: [] });
                                selectEndorseList({ payload: formValues , props: this.props })
                            },
                        });
                    },
                });
                
            }
        }
        if(type=='confirm'){
            unit.callConfirm()
        }else if(type=='commit')  {
           
            unit.callCommit()
        }

        
    };
   
    getValue = (values, type) => {
        this.setState({
            [type]: values,
        });
    };
    //导入
    getEndoresList=()=>{
        const {param} =this.state
        selectEndorseList({ props: this.props,payload:param });
    }
   
    
    handleImportFile = () => {
        this.setState((pre) => ({
            visibleFile: !pre.visibleFile
        }));
    };
    //导出
    downloadDetailInfo = e => {
        e.stopPropagation();
        const { dispatch } = this.props;
        const { param } = this.state;
        const {status,...allvalues}=param
        if(status&&status.length==1){
            allvalues.status=status[0]
        }else if(status&&status.length>1){
            allvalues.status=status.join(',')
        }
        console.log('param-33--',allvalues)
        dispatch({
            type:allDispatchType.exportEndorse,
            payload:allvalues||{},
            
        })
      };
    //转为本地<-->重新拉取
    pullOrLocal = (type) => {
        const { dispatch, formValues } = this.props;
        const { detailId, isHK } = this.state;
        dispatch({
            type: allDispatchType[type],
            payload: { id: detailId },
            callback: data => {
                // if (!data) return;
                selectEndorseList({ props: this.props, payload: formValues });
                selectArchivesDetailAndInfo({
                    type: allDispatchType.detail,
                    payload: { id: detailId, isHK },
                    props: this.props,
                    callback: data => {
                        this.setState({
                            recordStatus: data.status,
                            businessType:data.businessType
                        });
                    },
                });
            },
        });
    }

    modalEmpty = (type) => {
        if (type == 'add') {
            this.setState({
                detailId: '',
            })
        }
        this.setState((pre) => ({
            visibleEmpty: !pre.visibleEmpty
        }))
    }
   

    render() {
        const { endorseList, loading, form, isMobile, dictObject, emptyDetails, endorseDetail } = this.props;
        const { 
            businessType,
            expandForm,
            detailId, 
            visible, 
            recordStatus, 
            selectedRows, 
            isHK, 
            visibleEmpty,
            visibleFile,
            } = this.state;
        let detail = {};
        const commonParams = {
            getFieldDecorator: form.getFieldDecorator,
        };
        const getFieldDecorator=form.getFieldDecorator
        const firstFormItem = (
            <Form.Item label="处理情况">
                {getFieldDecorator('handlingInformation', {
                    initialValue:'FINISHED'
                })(
                    <AdSelect disabled={disabled} isExist={true} data={handling} />
                    
                )}
            </Form.Item>
            
        );
        const secondFormItem = (
            <AntdFormItem label="车牌号" code="vehicleId" {...commonParams}>
                <SearchSelect
                    dataUrl="tms/tms-vehicle/selectListByArchives"
                    url="tms/tms-oil/selectOilVehicleView_s" // selectedData只只有id时需要传url
                    selectedData={this.state.cars} // 选中值
                    multiple={false} // 是否多选
                    showValue="cartPlateOneNo"
                    searchName="cartPlate"
                    columns={columns1} // 表格展示列
                    onChange={values => this.getValue(values, 'cars')} // 获取选中值
                    scrollX={480}
                    id="ArchivesList_1"
                    allowClear={true}
                    payload={{ categoryList: ['HEADSTOCK', 'CARLOAD'] }} //筛选为整车和车头的
                />
            </AntdFormItem>
        );
        // secondForm 参数
        const otherFormItem = [
            [
                <AntdFormItem label="司机" code="driverId" {...commonParams}>
                    <SearchSelect
                        multiple={false} // 是否多选
                        dataUrl="tms/tms-driver-archives/selectDriverList"
                        url="tms/tms-driver-archives/selectDriverView_s"
                        selectedData={this.state.drivers} // 选中值
                        columns={columnsDriver} // 表格展示列
                        onChange={values => this.getValue(values, 'drivers')} // 获取选中值
                        id="ArchivesList_2"
                        scrollX={500}
                        allowClear={true}
                    />
                </AntdFormItem>,
            ],
            [
                // 所属公司
                <AntdFormItem label="是否在职" code="beWork" {...commonParams}>
                     <AdSelect disabled={disabled} isExist={true} data={beWork} />
                </AntdFormItem>,
                <AntdFormItem label="是否公司承担" code="beAssume" {...commonParams}>
                   <AdSelect disabled={disabled} isExist={true} data={beAssume} />
                </AntdFormItem>,
                <AntdFormItem label="处理方式" code="processMode" {...commonParams}>
                   <AdSelect disabled={disabled} isExist={true} data={processMode} />
                </AntdFormItem>,
            ],
            [

                <AntdFormItem label="交通违法时间" code="trafficOffenceTime" {...commonParams}>
                    <AntdDatePicker mode="range" />
                </AntdFormItem>,
                <AntdFormItem label="处理时间" code="handlingDate" {...commonParams}>
                    <AntdDatePicker mode="range" />
                </AntdFormItem>,
                 <AntdFormItem label="状态" code="status" {...commonParams}>
                     <AdSelect isExist={true} data={confirmState} mode="multiple" />
                </AntdFormItem>,
                // <AntdFormItem label="结算周期" code="settlementDate" {...commonParams}>
                //     <MonthPicker style={{ width: "100%" }} />
                // </AntdFormItem>,
            ],
            [
                <AntdFormItem label="交通违法项目" code="trafficOffenceProject" {...commonParams}>
                     <Input />
                     {/* <AdSelect disabled={disabled} isExist={true} data={dictObject[allDictList.traffic_offence]} /> */}
                </AntdFormItem>,
                // <AntdFormItem label="处理情况" code="handlingInformation" {...commonParams}>
                //      <AdSelect disabled={disabled} isExist={true} data={handling} />
                //      {/* {getFieldDecorator('handlingInformation', {
                //           rules: [{ required: true, message: '请输入加油时间' }],
                //           initialValue:'FINISHED'
                              
                //         })(
                        
                         
                //         )}    */}
                // </AntdFormItem>,
                <AntdFormItem label="交通违法地点" code="trafficOffenceAddress" {...commonParams}>
                    <Input />
                </AntdFormItem>,
                'operatorButtons'
            ]
        ];
        const selectFormParams = {
            firstFormItem,
            secondFormItem,
            otherFormItem,
            form,
            className: this.className,
            handleFormReset: this.handleFormReset,
            handleSearch: this.handleSearch,
            toggleForm: expandForm => {
                this.handleStateChange([{ expandForm }]);
            },
            code: codes.select,
        };

        const tableButtonsParams = {
            handleAdd: this.handleAdd,
            code: codes.addEndorse,
            addName: '+ 国内车行车档案',
            
            // rightButtons: (
            //     <AdButton
            //         style={{ marginLeft: 8 }}
            //         onClick={() => this.modalEmpty('add')}
            //         text="+ 新增违章记录"
            //         code={codes.addHK}
            //     />
            // ),
            rightButtonsFist: (
                <AdButton
                    type="primary"
                    style={{ marginLeft: 8 }}
                    onClick={() => this.motorcadeEmpty('YCD')}
                    text="新增"
                    code={codes.addEndorse}
                />

            ),
            buttons: (
                // <AdButton
                //     style={{ marginLeft: 8 }}
                //     disabled={!selectedRows.length > 0}
                //     onClick={() => this.endorseConfirm('commit', 0)} 
                //     // onClick={() => this.ceshi('commit', 0)} 
                //     text="批量提交"
                //     code={codes.commit}
                // />
                <Button.Group>
                    <AdButton
                    style={{ marginLeft: 8 }}
                    disabled={!selectedRows.length > 0}
                    onClick={() => this.endorseConfirm('commit', 0)} 
                    // onClick={() => this.ceshi('commit', 0)} 
                    text="批量提交"
                    code={codes.commit}
                   />
                    <AdButton onClick={() => this.handleImportFile()} text="导入" code={codes.import} />
                    <AdButton onClick={(e) => this.downloadDetailInfo(e)} text="导出" code={codes.export} />

                    
                    {/* <AdButton
                        disabled={!selectedRows.length > 0}
                        onClick={() => this.generatedBills('single')}
                        text={`生成账单${selectedRows.length > 0 ? '(' + selectedRows.length + ')' : ''}`}
                        code={codes.bill}
                    />*/}
                </Button.Group> 

            ),
        };

        // 详情 参数
        const disabled = recordStatus == 'SUBMITTED' ? true : false;

        const rightDrawParams = {
            isMobile,
            visible,
            title: '违章记录详情',
            code: codes.showDetail,
            closeDetail: this.handleStateChange.bind(this, [{ visible: false }]),
            buttons: (
                <>  <span>
                    <AdButton
                        onClick={() => this.removeEndorse(1)}
                        // disabled={!isBillStatus}
                        text="删除"
                        type="danger"
                        ghost
                        code={codes.remove}
                    />
                    <Button.Group style={{ marginLeft: 8 }}>
                        <AdButton
                            // disabled={!isBillStatus || detailsStatus !== 'WAIT'}
                            onClick={() => this.endorseConfirm('confirm')}
                            text="确认"
                            code={codes.confirm}
                        />
                        <AdButton
                            // disabled={!isBillStatus}
                            onClick={this.handleEdit}
                            text="编辑"
                            type="primary"
                            code={codes.edit}
                        />
                    </Button.Group>
                </span>
                </>
            ),
        };


        return (
            <Fragment>
                {/* 导入 弹框 */}
                <FileImport
                    visibleFile={visibleFile}
                    handleCancel={() => {
                        this.handleImportFile();
                    }}
                    urlImport={`tms/tms-endorsement/importEndorsementDetails`}
                    urlCase={`attachment/违章导入模板.xlsx`}
                    queryData={[this.getEndoresList]}
                    accept=".xls,.xlsx"
                />
                <SelectForm {...selectFormParams} />
                <TableButtons {...tableButtonsParams} />
                <StandardTable
                    // disabledRowSelected={true}
                    selectedRows={selectedRows}
                    onSelectRow={selectedRows => {
                        this.handleStateChange([{ selectedRows }]);
                    }}
                    loading={loading}
                    data={endorseList}
                    columns={this.columns}
                    onPaginationChange={this.handleStandardTableChange}
                    expandForm={expandForm}
                    className={this.className}
                    code={codes.page}
                    disabledSelectedRows={{ code: ['status'], value: ['CONFIRM'] }}
                    getCheckboxProps={record => {
                        const status = record.status;
                        const checked = status === 'CONFIRM';
                        return !checked;
                    }}
                />
                 <RightDraw {...rightDrawParams}>
                    {/* <OilTetails type="details" checkId={checkId} isMobile={isMobile} /> */}
                    <EndorseDetails type="details" checkId={detailId}  isMobile={isMobile} />

                </RightDraw>
                {
                    visibleEmpty && <EmptyArchivesForm
                        visible={visibleEmpty}
                        modalEmpty={this.modalEmpty}
                        detailId={detailId}
                    />
                }
            </Fragment>
        );
    }
}
